package cn.liccshop.core.backstage.sysUser.controller;


import cn.liccshop.core.backstage.sysRole.service.ISysRoleService;
import cn.liccshop.core.entity.ShopUser;
import cn.liccshop.core.entity.SysRole;
import cn.liccshop.core.entity.SysUser;
import cn.liccshop.core.backstage.sysUser.service.ISysUserService;
import cn.liccshop.core.utils.ObjectToOtherUtils;
import cn.liccshop.sys.cache.CommonCacheUtil;
import cn.liccshop.sys.constants.Constants;
import cn.liccshop.sys.entity.Result;
import cn.liccshop.sys.entity.ResultOfAdminLogin;
import cn.liccshop.sys.entity.UserElement;
import cn.liccshop.sys.exception.MySystemException;
import cn.liccshop.sys.utils.AESUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import cn.liccshop.sys.base.MyActionController;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description 用户表 前端控制器
 *
 * @author LiCC
 * @since 2019-04-05
 */
@RestController
@RequestMapping("/sysUser")
public class SysUserController extends MyActionController<SysUser> {

    @Autowired
    private ISysUserService liSysUserService;

    @Autowired
    private CommonCacheUtil commonCacheUtil;
    @Autowired
    private ISysRoleService sysRoleService;

    @Override
    protected IService<SysUser> getLiService(){
        return liSysUserService;
    }

    @Override
    @RequestMapping(L_DATA_INSERT)
    public Result dataInsert(@RequestBody SysUser entity) throws MySystemException {
        if (StringUtils.isBlank(entity.getLoginName())){
            throw new MySystemException("登录名异常", Constants.INVALID_PARM);
        }
        if (StringUtils.isBlank(entity.getPassword())){
            entity.setPassword(Constants.PASSWORD_OF_ADMIN);
        }
        entity.setPassword(AESUtil.encrypt(entity.getPassword()));
        return super.dataInsert(entity);
    }

    /**
     * 超级管理员添加或修改或重置管理员信息
     * @param entity
     * @return
     */
    @RequestMapping(value = "/sou")
    public Result saveAdminInfo(@RequestBody SysUser entity){
        boolean data = liSysUserService.saveAdminInfo(entity);
        return new Result().setCode(Constants.OK).setData(data).setMessage("操作成功");
    }

    @RequestMapping(value = "/delete")
    public Result deleteAdminInfo(@RequestBody SysUser entity) throws MySystemException {
        boolean data = liSysUserService.deleteAdminInfo(entity);
        return new Result().setCode(Constants.OK).setData(data).setMessage("删除成功");
    }

    /**
     * 管理员登陆
     * @param sysUser
     * @return
     * @throws MySystemException
     */
    @RequestMapping("/login")
    public Result login(@RequestBody SysUser sysUser) throws MySystemException {
        if (StringUtils.isBlank(sysUser.getLoginName())||StringUtils.isBlank(sysUser.getPassword())){
            throw new MySystemException("登录名或密码有误！", Constants.INVALID_PARM);
        }
        String token = liSysUserService.login(sysUser);
        Map<String, String> data = new HashMap<>();
        data.put("token",token);
        return new Result().setCode(Constants.OK).setData(data).setMessage("登录成功");
    }

    /**
     * 管理员登录后获取账号信息
     * @return
     * @throws MySystemException
     */
    @RequestMapping("/info")
    public Result getUserInfo() throws MySystemException {
        UserElement userElement = getUserInfoByToken();
        ResultOfAdminLogin data = liSysUserService.getUserInfo(userElement.getUserId());
        return new Result().setCode(Constants.OK).setData(data).setMessage("用户信息获取成功");
    }

    /**
     * 管理员登陆
     * @return
     * @throws MySystemException
     */
    @RequestMapping("/logout")
    public Result logout() {
        UserElement userElement = getUserInfoByToken();
        commonCacheUtil.delTokenWhenLogut(userElement);
        return new Result().setCode(Constants.OK).setMessage("退出成功");
    }
    /**
     * 管理员重置密码或头像
     * @return
     * @throws MySystemException
     */
    @RequestMapping("/restInfo")
    public Result restInfo(@RequestBody Map<String, Object> map) throws MySystemException {
        UserElement userElement = getUserInfoByToken();
        String userId = userElement==null?null:userElement.getUserId();
        if (StringUtils.isBlank(userId)){
            throw new MySystemException("用户未登录",Constants.UNAUTHEN);
        }
        String lastPassword = ObjectToOtherUtils.toString(map.get("lastPassword"));
        String firstPassword = ObjectToOtherUtils.toString(map.get("firstPassword"));
        String photo = ObjectToOtherUtils.toString(map.get("photo"));
        /** 获取用户信息 **/
        SysUser sysUser = liSysUserService.getById(userId);
        if (StringUtils.isNotBlank(lastPassword)&&StringUtils.isNotBlank(firstPassword)){
            lastPassword = AESUtil.encrypt(lastPassword);
            if (lastPassword.equals(sysUser.getPassword())){
                firstPassword = AESUtil.encrypt(firstPassword);
                liSysUserService.updateById(new SysUser().setId(userId).setPassword(firstPassword));
            } else {
                throw new MySystemException("原密码错误！，请联系超级管理员重置密码！", Constants.SYS_ERROR);
            }
        }
        if (StringUtils.isNotBlank(photo)){
            liSysUserService.updateById(new SysUser().setId(userId).setPhoto(photo));
        }
        return new Result().setCode(Constants.OK).setMessage("修改成功");
    }
    /**
     * 超级管理员获取所有消费者信息
     * @param page
     * @param size
     * @param map
     * @return
     */
    @RequestMapping(value = "/allInfo")
    public Result getUserAllInfo(@RequestParam("page") Integer page, @RequestParam("size") Integer size, @RequestBody Map<String, Object> map) throws MySystemException {
        IPage<SysUser> iPage = new Page<>(page, size);
        Wrapper<SysUser> wrapper = new QueryWrapper<>(new SysUser()).orderByAsc("create_date");;
        if (map.get("loginName")!=null){
            /** 手机号存在 **/
            ((QueryWrapper<SysUser>) wrapper).like("login_name",map.get("loginName"));
        }
        if (map.get("roleId")==null){
            throw new MySystemException("选择用户角色", Constants.INVALID_PARM);
        } else {
            List<Map<String,Object>> userIds = sysRoleService.selectUserIdByRoleId(ObjectToOtherUtils.toString(map.get("roleId")));
            List<String> userIdList = new ArrayList<>();
            for (Map<String, Object> userId : userIds){
                userIdList.add((String) userId.get("userId"));
            }
            ((QueryWrapper<SysUser>) wrapper).in("id", userIdList);
        }
        if (map.get("date")!=null){
            /** 筛选时间数据存在 **/
            String[] date = ObjectToOtherUtils.toString(map.get("date")).split(",");
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            ((QueryWrapper<SysUser>) wrapper).between("create_date", LocalDateTime.parse(date[0],df),LocalDateTime.parse(date[1],df));
        }
        liSysUserService.page(iPage, wrapper);
        return new Result().setCode(Constants.OK).setData(iPage);
    }

}

